package com.ts.notice.controller;

import com.ts.common.core.utils.Result;
import com.ts.notice.dto.SMSDto;
import com.ts.notice.utils.SMSUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sms")
@Slf4j
public class SMSController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SMSUtils smsUtils;

    private String SMSKey = "ts:notice:login:%s-%s";

    //获取验证码
    @GetMapping("/send")
    public Result send(String phone){

        //判断手机号是否为空
        if (phone.isEmpty()){
            return new Result().error(300,"手机号不能为空");
        }

        //生成一个四位数的验证码
        String code = RandomStringUtils.random(4,false,true);

        //将验证码保存到redis中
        String key = String.format(SMSKey,phone,code);
        redisTemplate.opsForValue().set(key,code,60, TimeUnit.SECONDS);

        //发送验证码
        SMSDto smsDto = new SMSDto();
        smsDto.setPhone(phone);
//        smsUtils.send(smsDto);
        log.debug("验证是：{}",code);

        return new Result().Viewok(null);
    }
}
